<?php
/**
 * 原生支付（扫码支付）及公众号支付的异步回调通知
 * 说明：需要在native.php或者jsapi.php中的填写回调地址。例如：http://www.xxx.com/wx/notify.php
 * 付款成功后，微信服务器会将付款结果通知到该页面
 */
header('Content-type:text/html; Charset=utf-8');
$mchid = '1481983162';          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
$appid = 'wxd90e0b89d1a1b0ad';  //公众号APPID 通过微信支付商户资料审核后邮件发送
$apiKey = '8934e7d15453e97507ef794cf7b0519d';   //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

//file_put_contents("log.txt", file_get_contents("php://input"));

$wxPay = new WxpayService($mchid,$appid,$apiKey);
$result = $wxPay->notify();
if($result){
    //完成你的逻辑
    //例如连接数据库，获取付款金额$result['cash_fee']，获取订单号$result['out_trade_no']，修改数据库中的订单状态等;
    file_put_contents("log.txt", json_encode($result));
	
    define('IN_MOBILE', true);
    
    define("DS", '/');
    define("APP_PATH",  dirname(dirname(__FILE__)).DS.'application'.DS);
    //session_start();
    $app  = new Yaf_Application(APP_PATH . "conf/application.ini");
    $app->bootstrap()->run();
    $ordermodel=new OrderModel();
    
    $out_trade_no_arr=explode("_", $result['out_trade_no']);
    $record['out_trade_no'] = $out_trade_no_arr[0];
    $record['orderid'] = $out_trade_no_arr[1];
    $record['ctime'] = time();
    
    $ordermodel->addweixin_paylog($record);
    
    $data['status']=2;
    $where['oid =?']=$record['orderid'];
    $ordermodel->updateorder($data,$where);
	
}else{
    echo 'pay error';
}
class WxpayService
{
    protected $mchid;
    protected $appid;
    protected $apiKey;
    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;
        $this->appid = $appid;
        $this->apiKey = $key;
    }
    public function notify()
    {
        $config = array(
            'mch_id' => $this->mchid,
            'appid' => $this->appid,
            'key' => $this->apiKey,
        );
        
        $postStr = file_get_contents("php://input") ? file_get_contents("php://input") : $GLOBALS["HTTP_RAW_POST_DATA"] ; 
        
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        
       
        if ($postObj === false) {
            die('parse xml error');
        }
        if ($postObj->return_code != 'SUCCESS') {
            die($postObj->return_msg);
        }
        if ($postObj->result_code != 'SUCCESS') {
            die($postObj->err_code);
        }
        $arr = (array)$postObj;
        unset($arr['sign']);
        if (self::getSign($arr, $config['key']) == $postObj->sign) {
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
            return $arr;
        }
    }
    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);
        $unSignParaString = self::formatQueryParaMap($params, false);
        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));
        return $signStr;
    }
    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }
}